package cn.fx.filters;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;

@Component //交给spring管理
@Slf4j // 日志
public class LoginCheckFilter implements GlobalFilter, Ordered {

    //创建日志器，可以使用slf4j提供德日志器进行日志打印
    private static final Logger log =  LoggerFactory.getLogger(RequestTimeFilter.class);

    //执行此filter的业务方法 exchange: 上下文对象，chain: filter的调用链对象
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        //判断请求路径是否包含login/register，如果不包含就拦截
        if(!path.endsWith("login") && !path.endsWith("register")){
            //从请求头中获取token，此处获取到的是一个集合
            List<String> token = request.getHeaders().get("token");
            log.info("用户的token信息: {}",token);

            //判断token请求头是否为空，如果为空抛出异常，说明未登录，响应nologin
            if(token == null || token.isEmpty()){
                // 1.响应对象
                ServerHttpResponse response = exchange.getResponse();
                // 2.构建错误结果
                HashMap<String,Object> data = new HashMap<>();
                // 3.设置响应信息
                data.put("code", 401);
                data.put("success", false);
                data.put("message","登录校验失败，请重新登录！");

                DataBuffer buffer = null;
                //  4.转换参数，包装buffer对象
                // 4.1.将数据转换为JSON，再转换为byte数组
                byte[] bytes = JSON.toJSONString(data).getBytes(StandardCharsets.UTF_8);
                // 4.2.将byte数组包装到DataBuffer对象中，用于响应给浏览器，构建响应内容
                buffer = response.bufferFactory().wrap(bytes);

                // 5.设置完成响应，不会继续执行后面的filter
                // 5.1.设置响应状态为401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                // 5.2.设置响应格式
                response.getHeaders().add("Content-Type","application/json;charset=UTF-8");

                // 6.把结果写给客户端
                return response.writeWith(Mono.just(buffer));
            }
        }

        log.info("Token不为空 ，放行");
        // 7.token不为空，继续执行后续filter
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
